package cn.example.filter;


import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HostFilter implements Filter {

    private static final String[] HOST_LIST = {"127.0.0.1", "localhost"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String host = response.getHeader("host");
        if (host != null && !checkBlankList(host)) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }
        filterChain.doFilter(request, response);
    }

    private boolean checkBlankList(String host) {
        boolean isAllow = false;
        for (String blankHost : HOST_LIST) {
            System.out.println("blankHost:" + blankHost);
            System.out.println("host:" + host);
            if (blankHost.contains(host)) {
                isAllow = true;
            }
        }
        return isAllow;
    }

    @Override
    public void destroy() {

    }
}